package com.wateray.ipassbook.persistence;

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.DaoManagerBuilder;
import com.wateray.ipassbook.commom.Constant;
import com.wateray.ipassbook.util.ResouceLoader;
import com.wateray.ipassbook.util.log4j.Log;

public class DaoConfig {

  private static final String resource = "com/wateray/ipassbook/persistence/dao.xml";
  private static final DaoManager daoManager;

  static {
    try {
      daoManager = newDaoManager(null);
      Properties props = Resources.getResourceAsProperties(Constant.DATABASE_PROPERTIES);
      String url = props.getProperty("url");
      String driver = props.getProperty("driver");
      String username = props.getProperty("username");
      String password = props.getProperty("password");
      Log.getLogger(DaoConfig.class);
      if (url.equals(Constant.DATABASE_URL)) {
        Class.forName(driver).newInstance();
//        Connection conn = DriverManager.getConnection(url, username, password);
        Connection conn = DriverManager.getConnection(url);
        try {
          ScriptRunner runner = new ScriptRunner(conn, false, false);
//          PropertyConfigurator.configure(ResouceLoader.getResouce(Constant.LOG4J_FILE));
          runner.setErrorLogWriter(null);
          runner.setLogWriter(null);
//          runner.runScript(Resources.getResourceAsReader("ddl/hsql/jpetstore-hsqldb-schema.sql"));
//          runner.runScript(Resources.getResourceAsReader("ddl/hsql/jpetstore-hsqldb-dataload.sql"));
        } finally {
          conn.close();
        }
      }
    } catch (Exception e) {
      throw new RuntimeException("Description.  Cause: " + e, e);
    }

  }

  public static DaoManager getDaoManager() {
    return daoManager;
  }

  public static DaoManager newDaoManager(Properties props) {
    try {
      Reader reader = Resources.getResourceAsReader(resource);
      return DaoManagerBuilder.buildDaoManager(reader, props);
    } catch (Exception e) {
      throw new RuntimeException("Could not initialize DaoConfig.  Cause: " + e, e);
    }
  }

}
